import React, { useEffect, useImperativeHandle } from 'react';
import { Radio, Form, Field, Input } from '@alifd/next';

const Operation = (props, ref) => {
  const { actionType } = props;
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const dataSource = props.dataSource || {};
  const field = Field.useField([]);
  useEffect(() => {
    field.reset();
    if (Object.keys(dataSource).length > 0) {
      const newValues = {
        id: dataSource.id,
        key: dataSource.key,
        value: dataSource.value,
        remark: dataSource.remark,
      };
      field.setValues(newValues);
    }
  }, [field, dataSource]);
  useImperativeHandle(ref, () => {
    return {
      getValues(callback) {
        field.validate((errors, values) => {
          if (errors) {
            return;
          }

          callback(values);
        });
      },
    };
  });
  const isPreview = actionType === 'preview';

  return (
    <>
      <Form
        isPreview={isPreview}
        fullWidth
        useLabelForErrorMessage
        field={field}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
      >
        <Form.Item label="参数名" required={!isPreview}>
          <Input name="key" />
        </Form.Item>
        <Form.Item label="参数值" required={!isPreview}>
          <Input name="value" />
        </Form.Item>
        <Form.Item label="备注">
          <Input name="remark" />
        </Form.Item>
      </Form>
    </>
  );
};

export default React.forwardRef(Operation);
